//
//  XTNetWorkTools.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/12.
//  Copyright © 2016年 肖霆. All rights reserved.
//


//*******AnyObject为任意类型，包含字典、数组、字符串等等很多类型

import UIKit
import AFNetworking




//请求方式枚举类型

enum RequestType : Int{
    case GET = 0
    case POST = 1
}
////新浪微博的appKey
//let WeiboAppKey = "4098451793"
////授权回调页(用户同意授权后，跳转到的页面)
//let WeiboRedirect_Uri = "http://www.baidu.com"



class XTNetWorkTools: AFHTTPSessionManager {
    //单例实例化方法
    static let sharedTools : XTNetWorkTools = {
    let tool = XTNetWorkTools()
        //添加可以接收的响应类型
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    
    //上传网络请求封装
    func requestUpload(url:String,params:AnyObject?,data:NSData,name:String,callBack:(response:AnyObject?,error:NSError?)->()){
        POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            //mimeType 资源类型 application/octet-stream  不确定类型的数据
            formData.appendPartWithFileData(data, name: name, fileName: "dontcare", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
            }) { (_, error) -> Void in
                callBack(response: nil, error: error)
        }
    
    }
    //网络GET／POST请求封装
    func request(requestType:RequestType,url:String,params:AnyObject?,callBack:(response:AnyObject?,error:NSError?)->()){
    
        //创建一个成功的闭包
        let successClosure = {(dataTask:NSURLSessionDataTask,response:AnyObject?)->() in
            
            callBack (response: response, error: nil)
        
        }
        
        //创建一个失败的闭包
        let failClosure = {(dataTask:NSURLSessionDataTask?,error:NSError)->() in
            callBack(response: nil, error: error)
            
        }
        
        //发起网络请求的方法
        if requestType == .GET{
            GET(url, parameters: params, progress: nil, success: successClosure, failure: failClosure)
            
        }else{
            POST(url, parameters: params, progress: nil, success: successClosure, failure: failClosure)
        }
        
        
        
    }
    
}
//发布微博相关请求

extension XTNetWorkTools{
    
    //发送纯文字微博
    func update(access_token:String,status:String,callBack:(response: AnyObject?, error: NSError?) -> ()){
        
        let url = "https://api.weibo.com/2/statuses/update.json"
        let params = [
                        "access_token" : access_token,
                        "status":status
        ]
        
        request(.POST, url: url, params: params, callBack: callBack)
    
    }
    //发送带图片微博的请求
    func upload(access_token:String,status:String,pic:UIImage,callBack:(response:AnyObject?,error:NSError?)->()){
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
                        "access_token":access_token,
                        "status":status,
        ]
        
        //将图片转换为二进制数据   Representation:表现
        let data = UIImageJPEGRepresentation(pic, 0.6)!
        requestUpload(url, params: params, data: data, name: "pic", callBack:callBack)
    
        
    }

}
//OAuth相关接口
extension XTNetWorkTools {
    //获取关注的人的微博的请求
    func requestStatus(accessToken:String,maxId:Int64 = 0,sinceId:Int64 = 0, callBack:(response:AnyObject?,error:NSError?)->()){
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        let params = [
            "access_token":accessToken,
            "max_id":"\(maxId)" ,//这不就变成字符串了吗？？？？？
            "since_id":"\(sinceId)"
        ]
        
        request(.GET, url: url, params: params, callBack: callBack)
        
    }
    
    
    //获取access token的请求
    func requestAccessToken(code:String,callBack:((response:AnyObject?,error:NSError?)->())){//保证此处的callBack与上面请求方式中所需的闭包类型（参数、返回值）一致
        
        
        //创建url
        let url = "https://api.weibo.com/oauth2/access_token"
        //设置传递内容参数
        let params = [
            "client_id":WeiboAppKey,
            "client_secret":WeiboAppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WeiboRedirect_Uri
        ]
        //调用上面的请求方式发送请求
        request(.POST, url: url, params: params, callBack:callBack)
    }
    
    
    //获取用户信息的请求
    func requestUserInfo(userAccount:XTUserAcount,callBack:((response:AnyObject?,error:NSError?)->())){
        //获取url
        let url = "https://api.weibo.com/2/users/show.json"
        //设置参数
        let params = [
            "access_token":userAccount.access_token!,
            "uid":"\(userAccount.uid)"
        ]
        
        request(.GET, url: url, params: params, callBack: callBack)
    }
}




















